package cn.buglife.springboot.controller.upload;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangjun on 15/12/4.
 */
@RestController
@RequestMapping(value = "/upload")
public class UploadController {

    /**
     * 处理异常
     *
     * @param ex
     * @param request
     * @return
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public @ResponseBody Map handleException(MaxUploadSizeExceededException ex, HttpServletRequest request) {
        Map result = new HashMap();
        result.put("error", "exceed max file sieze,upload error");
        return result;
    }

    @RequestMapping(value = "/simple", method = RequestMethod.POST)
    public Map simple(String name, MultipartFile file) {
        Map map = new HashMap();
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                return map;
            } catch (Exception e) {
                return map;
            }
        } else {
            return map;
        }

    }

}
